<?php

namespace App\Jobs;

use App\Lib\Notify\DingTalk;
use App\Models\WechatTemplateMsg;
use EasyWeChat\Factory;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendWechatMsg implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $data;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $data = $this->data;
        $user = $data['user'];
        $msg = $data['data'];
        $config = config('wechat.offical');
        $app = Factory::officialAccount($config);
        $sendData = $msg['tpl_content'];
        $tplId = $msg['tpl_id'];
        $openid = $user['openid'];
        $url = $msg['url'] ?? '';
        $req = [
            'touser'      => $openid,
            'template_id' => $tplId,
            //'url'         => 'http://baoming.xywlk.com/gprssearch.aspx?openid=ou00Qs4HW5q_2Sz6VO9zxoudDCVg',
            'data'        => $sendData,
        ];
        if ($url) {
            $req['url'] = $url;
        }
        $state = 2;
        try {
            $res = $app->template_message->send($req);

            if (isset($res['errcode']) && $res['errcode'] == 0) {
                $state = 1;
            }
        } catch (\Exception $e) {
            $res['errmsg'] = $e->getMessage();
        }


        WechatTemplateMsg::query()->create([
            'tpl_id'      => $tplId,
            'tpl_name'    => $msg['tpl_name'],
            'tpl_content' => $req,
            'openid'      => $openid,
            'name'        => $user['name'] ?: '',
            'result'      => $res ?: [],
            'state'       => $state,
            'msg'         => ($res['errmsg'] ?? '') ?: '',
            'msg_id'      => $msg['id'],
        ]);
    }

    public function failed(\Throwable $exception)
    {
        var_dump($exception->getMessage());
    }
}
